package reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

public class Test11 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class<?> c1 = Class.forName("reflection.Student2");
        // 通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);// @reflection.TableChen(value=db_student)
        }

        // 获得注解的Value的值
        TableChen tableChen = c1.getAnnotation(TableChen.class);
        String value = tableChen.value();
        System.out.println(value);// db_student

        // 获得字段的指定注解
        Field name = c1.getDeclaredField("name");
        FieldChen nameAnnotation = name.getAnnotation(FieldChen.class);
        System.out.println(nameAnnotation.columnName());// name
        System.out.println(nameAnnotation.type());// varchar
        System.out.println(nameAnnotation.length());// 3

    }
}

@TableChen("db_student")
class Student2 {

    @FieldChen(columnName = "id", type = "int", length = 10)
    private int id;
    @FieldChen(columnName = "age", type = "int", length = 10)
    private int age;
    @FieldChen(columnName = "name", type = "varchar", length = 3)
    private String name;

    public Student2() {
    }

    public Student2(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("{");
        sb.append("\"id\":")
                .append(id);
        sb.append(",\"age\":")
                .append(age);
        sb.append(",\"name\":\"")
                .append(name).append('\"');
        sb.append('}');
        return sb.toString();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

// 类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableChen {
    String value();
}

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldChen{
    String columnName();
    String type();
    int length();
}